<template>
  <div class="home card">
    <img class="home-bg" src="@/assets/images/welcome.png" alt="welcome" />
  </div>
  <div id="chat-box" v-if="chatOpen">
    <div class="chat-window">
      <div class="chat-header">
        <span>在线客服</span>
        <button @click="closeChat">关闭</button>
      </div>
      <div class="chat-content">
        <ul>
          <li v-for="(msg, index) in messages" :key="index">
            <div :class="msg.type === 'user' ? 'userMessage' : 'aiMessage'">
              <p>{{ msg.message }}</p>
            </div>
          </li>
        </ul>
      </div>
      <div class="chat-input">
        <input type="text" v-model="question" placeholder="请输入您的问题" />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
  <div id="floating-ball" @click="openChat" v-if="!chatOpen">
    <img src="@/assets/images/chaticon.png" alt="聊天" class="ball-icon" />
  </div>
</template>

<script setup lang="ts" name="home">
import { onMounted, ref } from "vue";
import { usePhoneStore } from "@/stores/phone";

const chatOpen = ref(false);
const userId = ref();
const question = ref();
const messages = ref([
  { type: "user", message: "您好，我想问你一些问题。" },
  { type: "ai", message: "你好，请问有什么问题需要咨询？" }
]);
const socket = ref();
const answer = ref();

onMounted(() => {
  creatSocket();
});

async function creatSocket() {
  const phoneStore = usePhoneStore();
  userId.value = BigInt(phoneStore.phone);
  socket.value = new WebSocket(`wss://192.168.58.147:8443/websocket/chat/${userId.value}`);
  socket.value.onopen = function () {
    console.log("websocket打开");
  };
  socket.value.addEventListener = event => {
    console.log(event);
    answer.value += event.data;
    messages.value.push({ type: "ai", message: answer.value });
  };
}
const openChat = () => {
  chatOpen.value = true;
};

const closeChat = () => {
  chatOpen.value = false;
};

const sendMessage = async () => {
  answer.value = "";
  messages.value.push({ type: "user", message: question.value });
  socket.value.send(
    JSON.stringify({
      question: question.value
    })
  );
  question.value = "";
};
</script>

<style scoped lang="scss">
@import "./index";
</style>
